﻿/* 
This file is part of Ingo Karstein's Excel Export project

**Do not remove this comment**

Please see the project homepage at CodePlex:
  http://spexcelexport.codeplex.com/

Please see my blog:
  http://ikarstein.wordpress.com

Licence: GPLv2
    Ingo Karstein's SharePoint 2010 Custom Ribbon Demo
    Copyright (C) 2011  Ingo Karstein, ikarstein@hotmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Diagnostics;
using System.Text;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Xml;
using System.Web;
using Microsoft.SharePoint.Utilities;

namespace ik.SharePoint2010.ExcelExport.Control
{
    [ParseChildren(false)]
    public partial class ExportExcelControl : UserControl
    {
        private bool IsInList = false;
        private XmlDocument parameters = null;

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if( IsInList )
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine(@"
<div align=""center"" style=""border:1px solid #7f7f7f;background: #aaaaaa;margin:5px;padding:5px""><a href=""#"" onclick=""javascript: return submit_$$$$();"">Export Excel</a></div>
                ");

                writer.Write(sb.ToString().Replace("$$$$", this.ID));
            };
        }


        protected override void AddParsedSubObject(object obj)
        {
            string inner = ( (LiteralControl)obj ).Text;
            if( !string.IsNullOrEmpty(inner) )
            {
                parameters = new XmlDocument();
                parameters.LoadXml(inner);
            }
        }

        protected void Page_Load(object sender, EventArgs args)
        {
            if( SPContext.Current == null )
            {
                IsInList = false;
                return;
            }
            if( SPContext.Current.List == null )
            {
                IsInList = false;
                return;
            }

            IsInList = true;

            string listParams = "";

            if( parameters != null )
            {
                string webSRU = SPContext.Current.Web.ServerRelativeUrl;
                string lstURL = SPContext.Current.List.DefaultViewUrl;
                if( lstURL.StartsWith(webSRU, StringComparison.InvariantCultureIgnoreCase) )
                    lstURL = lstURL.Substring(webSRU.Length);
                lstURL = lstURL.Substring(0, lstURL.LastIndexOf('/'));
                XmlNode x = parameters.SelectSingleNode("/Lists/List[@url=\"" + lstURL + "\"]");
                if( x != null )
                {
                    listParams = x.OuterXml;
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"
<script type=""text/javascript"" language=""javascript"">

function submit_$$$$()
{
    document.getElementById(""form$$$$"").setAttribute(""action"", """ + SPContext.Current.Web.Url + @"/_layouts/ik.SharePoint2010.ExcelExport/ExcelExportService.ashx"");
    document.getElementById(""form$$$$"").setAttribute(""method"", ""GET"");
    document.forms[""form$$$$""].submit(); 
    return false;
}

function addEvent_$$$$( obj, type, fn )
{
   if (obj.addEventListener) {
      obj.addEventListener( type, fn, false );
   } else if (obj.attachEvent) {
      obj[""e""+type+fn] = fn;
      obj[type+fn] = function() { obj[""e""+type+fn]( window.event ); }
      obj.attachEvent( ""on""+type, obj[type+fn] );
   }
}

function removeEvent_$$$$( obj, type, fn )
{
   if (obj.removeEventListener) {
      obj.removeEventListener( type, fn, false );
   } else if (obj.detachEvent) {
      obj.detachEvent( ""on""+type, obj[type+fn] );
      obj[type+fn] = null;
      obj[""e""+type+fn] = null;
   }
}

addEvent_$$$$(window, ""load"", function(){ createform_$$$$(); } );

function createform_$$$$()
{
    var newform = document.createElement(""form"");
    var aspform = document.getElementById(""" + this.Page.Form.ClientID + @""");

    newform.setAttribute(""method"", ""POST"");
    newform.setAttribute(""target"", ""_blank"");
    newform.setAttribute(""name"", ""form$$$$"");
    newform.setAttribute(""id"", ""form$$$$"");
    newform.setAttribute(""action"", """+SPContext.Current.Web.ServerRelativeUrl+@"/_layouts/ik.SharePoint2010.ExcelExport/ExcelExportService.ashx"");

    var newhiddenfield1=document.createElement(""input"");
    newhiddenfield1.setAttribute(""type"",""hidden"");
    newhiddenfield1.setAttribute(""name"", ""ee_$$$$_listName"");
    newhiddenfield1.setAttribute(""value"", """ + SPContext.Current.List.ID.ToString() + @""");
    newform.appendChild(newhiddenfield1);

    var newhiddenfield2=document.createElement(""input"");
    newhiddenfield2.setAttribute(""type"",""hidden"");
    newhiddenfield2.setAttribute(""name"", ""ee_$$$$_view"");
    newhiddenfield2.setAttribute(""value"", """ + SPContext.Current.ViewContext.ViewId.ToString() + @""");
    newform.appendChild(newhiddenfield2);

    var newhiddenfield5=document.createElement(""input"");
    newhiddenfield5.setAttribute(""type"",""hidden"");
    newhiddenfield5.setAttribute(""name"", ""ee_$$$$_query"");
    newhiddenfield5.setAttribute(""value"", """ + HttpUtility.HtmlEncode(SPContext.Current.ViewContext.View.Query) + @""");
    newform.appendChild(newhiddenfield5);

    var newhiddenfield3=document.createElement(""input"");
    newhiddenfield3.setAttribute(""type"",""hidden"");
    newhiddenfield3.setAttribute(""name"", ""ee_$$$$_url"");
    newhiddenfield3.setAttribute(""value"", document.parentWindow.location.href);
    newform.appendChild(newhiddenfield3);

    var newhiddenfield4=document.createElement(""input"");
    newhiddenfield4.setAttribute(""type"",""hidden"");
    newhiddenfield4.setAttribute(""name"", ""ee_$$$$_params"");
    newhiddenfield4.setAttribute(""value"", """ + HttpUtility.HtmlEncode(listParams) + @""");
    newform.appendChild(newhiddenfield4);

    aspform.parentNode.insertBefore(newform, aspform);
};
</script>
");

            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "exportexcel_load", sb.ToString().Replace("$$$$", this.ID));
        }
    }
}
